package handler

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"log"
	"net/http"
	v1 "server_go/api/v1"
	"server_go/internal/service"
)

type FileHandler interface {
	UploadFile(ctx *gin.Context)
	DeleteFile(ctx *gin.Context)
	GetFileInfo(ctx *gin.Context)
	UploadAvatar(ctx *gin.Context)
}

type fileHandler struct {
	*Handler
	fileService service.FileService
}

func NewFileHandler(handler *Handler, fileService service.FileService) FileHandler {
	return &fileHandler{
		Handler:     handler,
		fileService: fileService,
	}
}

func (h *fileHandler) UploadFile(ctx *gin.Context) {
	req := new(v1.UploadFileRequest)
	if err := ctx.ShouldBind(&req); err != nil {
		h.logger.Error("params error", zap.Any("error", err))
		v1.HandleError(ctx, http.StatusBadGateway, v1.ErrBadGateway, nil)
		return
	}
	h.logger.Info("UploadFile Information", zap.Any("req", req))

	resp, err := h.fileService.UploadFile(ctx, req)
	if err != nil {
		h.logger.Error("UploadFile error", zap.Any("error", err))
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, resp)
}

func (h *fileHandler) DeleteFile(ctx *gin.Context) {
	req := new(v1.DeleteFileRequest)
	if err := ctx.ShouldBind(&req); err != nil {
		h.logger.Error("params error", zap.Any("error", err))
		v1.HandleError(ctx, http.StatusBadGateway, v1.ErrBadGateway, nil)
		return
	}

	h.logger.Info("DeleteFile Information")

	resp, err := h.fileService.DeleteFile(req)

	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}

	v1.HandleSuccess(ctx, resp)
}
func (h *fileHandler) GetFileInfo(ctx *gin.Context) {
	req := new(v1.GetFileInfoRequest)
	if err := ctx.ShouldBindUri(&req); err != nil {
		log.Printf("Bind error: %v, Request Body: %+v", err, req)
		h.logger.Error("params error", zap.Any("error", err), zap.Any("req", req))
		v1.HandleError(ctx, http.StatusBadGateway, v1.ErrBadGateway, nil)
		return
	}

	h.logger.Info("GetFileInfo Information")

	resp, err := h.fileService.GetFileInfo(req)

	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, resp)

}

func (h *fileHandler) UploadAvatar(ctx *gin.Context) {
	req := new(v1.UploadAvatarReq)
	if err := ctx.ShouldBind(&req); err != nil {
		h.logger.Error("params error", zap.Any("error", err), zap.Any("req", req))
		v1.HandleError(ctx, http.StatusBadGateway, v1.ErrBadGateway, nil)
		return
	}

	h.logger.Info("UploadAvatar Information")

	resp, err := h.fileService.UploadAvatar(ctx, req)

	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}

	v1.HandleSuccess(ctx, resp)

}
